package cn.ubeta.b2c.product;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.TextView;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import cn.ubeta.b2c.EmbeddedData;
import cn.ubeta.b2c.HomeActivity;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.api.ApiProduct;
import cn.ubeta.b2c.bean.BannerInfo;
import cn.ubeta.b2c.bean.ProductInfo;
import cn.ubeta.b2c.bean.StockInfo;
import cn.ubeta.b2c.common.AnalyseActivity;
import cn.ubeta.b2c.common.CartCommon;
import cn.ubeta.b2c.common.ListFragment;
import cn.ubeta.b2c.unity.UnityParams;
import cn.ubeta.b2c.utils.Constants;
import cn.ubeta.b2c.utils.TitleBarHelper;
import cn.ubeta.b2c.utils.ToastHelper;
import cn.ubeta.b2c.widget.TitleBar;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static cn.ubeta.b2c.product.ProductListFragment.setResImage;

/**
 * Created by denny on 16/8/23.
 */

public class ProductDetail extends AnalyseActivity {

    public final static String PARAM_PRODUCT_INFO = "productInfo";

    //private ViewPager mViewPager;
    //private PagerAdapter mAdapter;

    protected View mViewBanner;
    protected ViewStub mVsBanner;
    private TitleBar mTitleBar;
    //private RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_product_detail);

        TitleBarHelper.setRightAction(this, "主页", v -> HomeActivity.gotoHome(this));

        ProductInfo item = getIntent().getParcelableExtra(PARAM_PRODUCT_INFO);
        initViews(item);

        boolean enabled = item.hasModel();
        findViewById(R.id.tv_3d).setEnabled(enabled);
        findViewById(R.id.tv_ar).setEnabled(enabled);
    }

    /**
     * 初始化详情
     */
    private void initViews(ProductInfo item) {
        findViewById(R.id.tv_ar).setOnClickListener(v -> {
            // TODO AR目前仅支持Tango手机
            ToastHelper.show("AR目前仅支持Tango手机");
        });
        findViewById(R.id.tv_3d).setOnClickListener(v -> gotoUnity(item, true));

        // 标题栏返回按钮
        mTitleBar = (TitleBar) findViewById(cn.ubeta.b2c.R.id.title_bar);
        mTitleBar.setLeftClickListener(v -> finish());

        mVsBanner = (ViewStub) findViewById(R.id.vs_banner);

        // 商品图
        List<BannerInfo> array = new ArrayList<>();
        int[] imgRes = item.getDetailImg();
        if (imgRes != null) {
            for (int res : imgRes)
                array.add(new BannerInfo(item.getSkuId(), res));
        }
        setBanner(array);

        // 相关商品,后面四个
        int[] resIds = new int[] {R.id.ll_related_product_1, R.id.ll_related_product_2, R.id.ll_related_product_3, R.id.ll_related_product_4};
        List<ProductInfo> list = EmbeddedData.getBrandProduct(item.getSkuId(), item.getBrandId(), resIds.length);
        for (int i = 0; i < 4; ++i) {
            View  view = findViewById(resIds[i]);
            if (i < list.size()) {
                bindRelatedProduct(view, list.get(i));
                view.setVisibility(VISIBLE);
            } else {
                if ((i == 1 && list.size() == 1) || (i == 3 && list.size() == 3))
                    view.setVisibility(INVISIBLE);
                else
                    view.setVisibility(GONE);
            }
        }

        // 标题,价格,描述
        ((TextView)findViewById(R.id.tv_name)).setText(item.getName());
        ((TextView)findViewById(R.id.tv_price)).setText(item.getDisplayPrice());
        ((TextView)findViewById(R.id.tv_checkout_price)).setText(item.getDisplayPrice());
        ((TextView)findViewById(R.id.tv_desc)).setText(item.getDesc());

        // 立即购买
        findViewById(R.id.tv_checkout).setOnClickListener(v -> CartCommon.checkout(this, item));

        // 获取库存
        ApiProduct.getProductStock(item.getSkuId(), new Callback<StockInfo>() {
            @Override
            public void onResponse(Call<StockInfo> call, Response<StockInfo> response) {
                // TODO 库存展示？
                if (response.body() != null && response.body().getData() != null) {
                    ToastHelper.debug("" + response.body().getData().get(0).getStock());
                }
            }

            @Override
            public void onFailure(Call<StockInfo> call, Throwable t) {

            }
        });
    }

    /**
     * 绑定相关商品数据
     * @param root
     * @param info
     */
    private void bindRelatedProduct(View root, ProductInfo info) {
        // 名字
        ((TextView)(root.findViewById(R.id.tv_name))).setText(info.getName());
        // 价格
        ((TextView)(root.findViewById(R.id.tv_price))).setText(info.getDisplayPrice());

        // 图片
        SimpleDraweeView img = ((SimpleDraweeView)root.findViewById(R.id.sv_product));
        img.setOnClickListener(v -> ProductDetail.gotoDetail(this, info));
        setResImage(img, info.getListImg());

        // 添加购物车
        root.findViewById(R.id.tv_add_cart).setOnClickListener(v -> {
            if (info.getPrice() == 0)
                ToastHelper.show("暂无价格，清重试");
            else
                CartCommon.checkout(this, info);
        });
    }

    /**
     * 设置banner
     */
    public void setBanner(List<BannerInfo> data) {
        if (mViewBanner == null) {
            mViewBanner = mVsBanner.inflate();
        }

        ListFragment.setBanner(this, data, mViewBanner);
    }

    /**
     * 跳转到详情
     * @param context
     * @param item
     */
    public static void gotoDetail(Context context, ProductInfo item) {
        Intent intent = new Intent(context, ProductDetail.class);
        intent.putExtra(ProductDetail.PARAM_PRODUCT_INFO, item);
        context.startActivity(intent);
        if (context instanceof Activity)
            ((Activity)context).overridePendingTransition(R.anim.in_right_to_left, android.R.anim.fade_out);
    }

    /**
     * 跳转AR/3D
     * @param item
     */
    private void gotoUnity(ProductInfo item, boolean is3d) {
        //gotoAr(item, is3d);
        Class clz = null;
        try {
            //clz = Class.forName("cn.ubeta.b2c.JdUnityActivity");
            clz = Class.forName("com.google.unity.GoogleUnityActivity");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (clz == null) {
            ToastHelper.show("Unity配置错误");
            return;
        }
        Intent intent = new Intent(this, clz);
        intent.putExtra(UnityParams.PARAM_MODEL_SKUID, item.getSkuId());
        intent.putExtra(UnityParams.PARAM_IS_3D, is3d);
        String thirtyPart = EmbeddedData.getThirtyPart(item.getBrandId(), item.getSkuId());
        if (!TextUtils.isEmpty(thirtyPart)) {
            intent.putExtra(UnityParams.PARAM_THIRTY_PART, thirtyPart);
        }
        startActivity(intent);
    }

    /**
     * 跳转AR/3D
     * @param item
     */
    private void gotoAr(ProductInfo item, boolean is3d) {
        Intent intent = new Intent();
        intent.setClassName(this, "cn.ubeta.b2c.ar.PlaneFittingActivity");
        startActivity(intent);
    }

    /*
    @Override
    protected TitleBar getTitleBar() {
        return mTitleBar;
    }
    */

    class ViewPagerAdapter extends PagerAdapter {

        private List<ProductInfo.ImageInfo> array;

        public ViewPagerAdapter(List<ProductInfo.ImageInfo> array) {
            this.array = array;
        }

        @Override
        public int getCount() {
            return array != null ? array.size() : 0;
        }

        // 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }


        // PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView((View) object);
        }

        // 当要显示的图片可以进行缓存的时候，会调用这个方法进行显示图片的初始化，我们将要显示的ImageView加入到ViewGroup中，然后作为返回值返回即可
        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(getResources());
            GenericDraweeHierarchy hierarchy = builder
                    .setFadeDuration(300)
                    .setPlaceholderImage(R.drawable.placeholder_small)
                    .build();
            SimpleDraweeView svPic = new SimpleDraweeView(ProductDetail.this);
            svPic.setHierarchy(hierarchy);
            view.addView(svPic);
            String url = array.get(position).imgUrl;
            if (!TextUtils.isEmpty(url)) {
                svPic.setImageURI(Uri.parse(Constants.IMG_SERVER_HOST + url));
            }
            return svPic;

        }
    }
}
